//
// Copyright (c) 2009-2011, chunquedong
//
// This file is part of ChunMap project
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE(Version >=3)
//
// History:
//   2011-05-05  Jed Young  Creation
//

using fwt
using gfx

using chunmapModel

**
** RectangleTool
**
@Js
abstract class RectangleTool : Tool
{
  private Int x := 0
  private Int y := 0
  private Bool draging := false
  protected Envelope? envelope
  private Color color := Color.black

  override Void actionEvent(Event e)
  {
    if (e.button != 1 && e.id != EventId.mouseMove) return

    switch (e.id)
    {
      case EventId.mouseDown: mousePressed(e)
      case EventId.mouseUp: mouseReleased(e)
      case EventId.mouseMove: mouseDragged(e)
      default: return
    }
  }

  private Void mouseDragged(Event e)
  {
    if (!draging) return

    envelope = Envelope(x.toFloat, y.toFloat, e.pos.x.toFloat, e.pos.y.toFloat)
    minx := envelope.minX.toInt
    miny := envelope.minY.toInt
    width := envelope.width.toInt
    height := envelope.height.toInt

    map.paintOnBuffer |g|
    {
      map.drawOriginImage(g, 0, 0)
      g.drawRect(minx, miny, width, height)
    }

    e.consume
    map.repaint
  }

  private Void mousePressed(Event e)
  {
    draging = true
    x = e.pos.x
    y = e.pos.y
    e.consume
  }

  private Void mouseReleased(Event e)
  {
    if (draging)
    {
      if (envelope != null)
      {
        finished
      }

      //reset
      draging = false
      x = 0
      y = 0
      envelope = null
      e.consume
    }
  }

  protected abstract Void finished()
}

